﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using Core;
using Core.ChannelProtocol;
using Core.DeviceProtocol;
using Core.Helper;
using Core.Model;
using Core.Msg;
using log4net;

namespace UdpChannel
{
    public sealed class UdpChannel : BaseChannel
    {
        private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private Thread _channelThread;
        private bool _running;
        private IPEndPoint _endPoint { get; set; }
        private readonly Queue<RxTxCommand> _sendCommands = new Queue<RxTxCommand>();
        private readonly Queue<RxTxCommand> _insertCommands = new Queue<RxTxCommand>();
       
        public UdpChannel(Channel channel)
        {
            try
            {
                ChlInfo = channel;
                ChlInfo.PollingDelay = channel.PollingDelay < 5 ? 5 : channel.PollingDelay;
                _endPoint = new IPEndPoint(IPAddress.Parse(ChlInfo.Ip), ChlInfo.Port);
                List<Device> devs = Global.DataAccess.GetDevices(ChlInfo.Id);
                if (devs != null)
                {
                    foreach (Device dev in devs)
                    {
                        LoadProtocol(dev);
                    }
                }
            }
            catch
            {
            }
        }

       

        private void ThreadProc()
        {
            while (Running)
            {
                if (_sendCommands.Count > 0 || _insertCommands.Count > 0)
                {
                    ThreadPool.QueueUserWorkItem(callBack =>
                    {
                        bool connectException = false;
                        try
                        {
                            RxTxCommand cmd;
                            if (_insertCommands.Count > 0)
                            {
                                cmd = _insertCommands.Dequeue();
                            }
                            else
                            {
                                cmd = _sendCommands.Dequeue();
                            }
                            var _client = new UdpClient();
                            var tokenSource = new CancellationTokenSource();
                            var token = tokenSource.Token;
                            var client = _client;
                            var t = System.Threading.Tasks.Task.Factory.StartNew(() =>
                            {
                                try
                                {
                                    client.Connect(_endPoint);
                                    Connected = true;
                                }
                                catch
                                {
                                    connectException = true;
                                    Connected = false;
                                }
                            }, token);
                            if (!t.Wait(1000, token)) // 等待1秒 避免Socket等待超时太长
                            {
                                connectException = true;
                                tokenSource.Cancel();
                            }
                            if (connectException)
                            {
                                // 超时处理
                            }

                            if (cmd != null)
                            {
                                Write(cmd, _client);
                                RaiseMessageEvent(cmd);
                            }
                             _client.Close();
                        }
                        catch (Exception ex)
                        {
                            _log.Info(ex.Message);
                        }
                    });
                }
                Thread.Sleep(ChlInfo.PollingDelay);
            }
        }
        private bool _connected = true;
        public override bool Connected
        {
            get => _connected;
            protected set
            {
                if (!_connected.Equals(value))
                {
                    _connected = value;
                }
                if (!_connected)
                {
                    foreach (KeyValuePair<string, BaseDevProtocol> devProtocol in protocols)
                    {
                        devProtocol.Value.Dev.IsConnected = false;
                        devProtocol.Value.DataItems.ForEach(sss => sss.CurValue = 0);
                    }
                }
            }
        }

        public override bool Running
        {
            get => _running;
            set
            {
                if (!_running.Equals(value))
                {
                    _running = value;
                }
            }
        }
        public override bool Start()
        {
            try
            {
                if (!Connected)
                {
                    UdpClient client;
                    var tokenSource = new CancellationTokenSource();
                    var token = tokenSource.Token;
                    var t = System.Threading.Tasks.Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (!Connected)
                            {
                                Stop();
                               
                                client = new UdpClient();
                                client.Client.SendTimeout = ChlInfo.WriteTimeout;
                                client.Client.ReceiveTimeout = ChlInfo.ReadTimeout;
                                client.Connect(_endPoint);
                                Connected = true;
                                _channelThread = new Thread(ThreadProc);
                                _channelThread.IsBackground = true;
                                Running = true;
                                _channelThread.Start();
                                client?.Close();
                            }
                        }
                        catch //(Exception ex)
                        {
                            Connected = false;
                        }
                    }, token);
                    if (!t.Wait(1500, token)) // 等待1.5秒 避免Socket等待超时太长
                    {
                        tokenSource.Cancel();
                        _log.Error("通道连接超时:" + ChlInfo.Name);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                Running = false;
                return false;
            }
            return true;
        }

        public override void Stop()
        {
            try
            {
                Running = false;
                Connected = false;
                _channelThread?.Abort();
                base.Stop();
            }
            catch //(Exception e)
            {
                //_log.Error(e.Message);
            }
        }

        protected override bool Connect(bool log = false)
        {
            return false;
        }

        public override void PutCommand(RxTxCommand cmd)
        {
            if (cmd != null)
            {
                _sendCommands.Enqueue(cmd, 100);
            }
        }

        public override void PutInsertCommand(RxTxCommand cmd)
        {
            if (cmd != null)
            {
                _sendCommands.Enqueue(cmd, 100);
            }
        }

        public override RxTxCommand PostToExcute(string devId, string operId)
        {
            if (protocols.ContainsKey(devId))
            {
                RxTxCommand cmd = protocols[devId].PostToExcute(operId);
                PutCommand(cmd);
                return cmd;
            }
            return null;
        }

        public override RxTxCommand PostToExcute(string devId, string operId, string[] paras)
        {
            if (protocols.ContainsKey(devId))
            {
                RxTxCommand cmd = protocols[devId].PostToExcute(operId, paras);
                PutCommand(cmd);
                return cmd;
            }
            return null;
        }

        public bool Write(RxTxCommand cmd,UdpClient client)
        {
            if (cmd == null || client == null )
            {
                return false;
            }
            try
            {
                cmd.SendTime = DateTime.Now;
                byte[] bytes = cmd.SendBytes;

                if (bytes != null && bytes.Length > 0)
                {
                    client.Client.SendTimeout = ChlInfo.WriteTimeout;
                    client.Send(bytes, 0, _endPoint);
                    if (cmd.NeedReply)
                    {
                        try
                        {
                            var ipend = _endPoint;
                            client.Client.ReceiveTimeout = ChlInfo.ReadTimeout;
                            byte[] buffer = client.Receive(ref ipend);
                            List<byte> tempbuffer = new List<byte>();
                            int count = 3;
                            while (buffer.Length> 0)
                            {
                                tempbuffer.AddRange(buffer);
                                count--;
                                if (count <= 0)
                                    break;
                                buffer = client.Receive(ref ipend);
                            }
                            cmd.ReceiveBytes = tempbuffer.ToArray();
                        }
                        catch (Exception ex)
                        {
                            _log.Error("操作反馈异常:" + ex.Message);
                        }
                    }
                    client.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return false;
        }

    }
}
